package top.dark.product.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.dark.common.utils.PageUtils;
import top.dark.common.utils.Query;

import top.dark.product.dao.ProductAttrValueDao;
import top.dark.product.entity.ProductAttrValueEntity;
import top.dark.product.service.AttrService;
import top.dark.product.service.ProductAttrValueService;
import top.dark.product.vo.SkuInfoUpEsVo;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoUpEsVo.Attrs> getAttrsBysSpuIdAndSearchType(Long spuId) {
        // 根据spuId查出所有包含的属性信息
        List<ProductAttrValueEntity> productAttrValueEntities = this.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> ids = productAttrValueEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        // 根据attrIds查出所有能被检索的属性id,剔除掉不需要被检索的属性信息
        List<Long> attrIds = attrService.listByIdsAndSearchType(ids);
        Set<Long> idSet = new HashSet<>(attrIds);
        List<SkuInfoUpEsVo.Attrs> attrs = productAttrValueEntities.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuInfoUpEsVo.Attrs attr = new SkuInfoUpEsVo.Attrs();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                }).collect(Collectors.toList());
        return attrs;
    }

}